package coop.bancocredicoop.proyectos.gd.query.document;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.Transaction;

import coop.bancocredicoop.proyectos.gd.domain.Document;
import coop.bancocredicoop.proyectos.gd.hibernate.HibernateUtil;

public class FindDocumentPreviousLastVersion {

	public Document run(Document document) throws Exception {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		Document result = null;

		try {
			tx = session.beginTransaction();

			result = _run(document, session);

			tx.commit();
		}
		catch (Exception e) {
			if (tx!=null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		return result;

	}

	private Document _run(Document document, Session session) throws Exception {

		String strQuery = " from Document " +
				" where deleteDate is null " +
				" and customer = :customer " +
				" and documentType = :documentType " +
				" and realVersion = :realVersion ";

		Query query = session.createQuery(strQuery);

		query.setEntity("customer", document.getCustomer());
		query.setEntity("documentType", document.getDocumentType());
		query.setLong("realVersion", document.getRealVersion() - 1);

		return (Document) query.uniqueResult();

	}

}
